package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupItemMapper;
import com.itheima.health.dao.CheckitemMapper;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessException;
import com.itheima.health.pojo.CheckGroupItem;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.service.CheckitemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService
@Slf4j
public class CheckitemServiceImpl implements CheckitemService {

    @Autowired
    private CheckitemMapper checkitemMapper;

    @Autowired
    private CheckGroupItemMapper checkGroupItemMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.info("检查项-检查项service层分页查询传参 ："+queryPageBean);
        //使用分页插件分页 传入分页参数 当前页码及每页条数 自动计算起始页码
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //分页查询
        Page<CheckItem> page = checkitemMapper.findByPage(queryPageBean.getQueryString());
        //封装返回值
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        log.info("检查项-检查项service层封装好的返回值内容是："+pageResult);
        return pageResult;
    }

    @Override
    public void add(CheckItem checkItem) {
        log.info("检查项-检查项service层新增检查项传参："+checkItem);
        checkitemMapper.insertSelective(checkItem);
    }

    @Override
    public void delete(Integer id) {
        log.info("检查项-检查项service层删除检查项传参："+id);
        CheckGroupItem checkGroupItem = new CheckGroupItem();
        checkGroupItem.setCheckitemId(id);
        //先查询该检查项下有没有子项，如果得到的数为0那么代表没有，可以删除
        int count = checkGroupItemMapper.selectCount(checkGroupItem);
        if (count>0){//不能删除
            //自定义异常
            throw new BusinessException("该检查项还有子项不能删除！！");
        }
        //运行到这里说明没有，可以删除该检查项
        checkitemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public CheckItem findById(Integer id) {
        log.info("检查项-检查项service层根据id查询检查项传参："+id);
        return checkitemMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(CheckItem checkItem) {
        log.info("检查项-检查项service层修改检查项传参："+checkItem);
        checkitemMapper.updateByPrimaryKeySelective(checkItem);
    }
}
